using Microsoft.EntityFrameworkCore;
using MESData.ErrorCode;
using MESData.Infrastucture;
using MESData.ProductionPlan.API.DTO;

namespace MESData.ProductionPlan.API.Services
{
    /// <summary>
    /// 销售订单服务实现类
    /// </summary>
    public class SalesOrderService : ISalesOrderService
    {
        private readonly MyDbcontext _context;

        public SalesOrderService(MyDbcontext context)
        {
            _context = context;
        }

        /// <summary>
        /// 分页查询所有销售订单
        /// </summary>
        public async Task<ApiPageing<SalesOrderResultDto>> GetSalesOrdersAsync(SalesOrderQueryDto queryDto)
        {
            try
            {
                var query = _context.SalesOrders
                    .Where(so => !so.IsDeleted)
                    .AsQueryable();

                // 应用查询条件
                if (!string.IsNullOrEmpty(queryDto.SalesOrderNumberOrSubject))
                {
                    query = query.Where(so => 
                        so.SalesOrderNumber.Contains(queryDto.SalesOrderNumberOrSubject) ||
                        so.SalesOrderSubject.Contains(queryDto.SalesOrderNumberOrSubject));
                }

                if (!string.IsNullOrEmpty(queryDto.CustomerName))
                {
                    query = query.Where(so => so.CustomerName.Contains(queryDto.CustomerName));
                }

                if (queryDto.SalesDateStart.HasValue)
                {
                    query = query.Where(so => so.SalesDate >= queryDto.SalesDateStart.Value);
                }

                if (queryDto.SalesDateEnd.HasValue)
                {
                    query = query.Where(so => so.SalesDate <= queryDto.SalesDateEnd.Value);
                }

                if (!string.IsNullOrEmpty(queryDto.PurchaseStatus))
                {
                    query = query.Where(so => so.PurchaseStatus == queryDto.PurchaseStatus);
                }

                // 获取总数
                var totalCount = await query.CountAsync();

                // 分页查询（先不在投影中调用实例方法）
                var salesOrders = await query
                    .OrderByDescending(so => so.CreateTime)
                    .Skip((queryDto.PageIndex - 1) * queryDto.PageSize)
                    .Take(queryDto.PageSize)
                    .Select(so => new SalesOrderResultDto
                    {
                        Id = so.Id,
                        SalesOrderNumber = so.SalesOrderNumber,
                        SalesOrderSubject = so.SalesOrderSubject,
                        CustomerName = so.CustomerName,
                        SalesDate = so.SalesDate,
                        PurchaseStatus = so.PurchaseStatus,
                        ItemSummary = string.Empty,
                        CreateTime = so.CreateTime
                    })
                    .ToListAsync();

                // 逐条填充物品概要，避免EF在投影阶段捕获实例方法
                foreach (var item in salesOrders)
                {
                    item.ItemSummary = await GetItemSummaryAsync(item.Id);
                }

                var totalPage = (int)Math.Ceiling((double)totalCount / queryDto.PageSize);

                return new ApiPageing<SalesOrderResultDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "查询成功",
                    TotaCount = totalCount,
                    TotaPage = totalPage,
                    PageData = salesOrders
                };
            }
            catch (Exception ex)
            {
                return new ApiPageing<SalesOrderResultDto>
                {
                    Code = ApiEnum.Error,
                    Msg = $"查询失败：{ex.Message}",
                    Data = null,
                    TotaCount = 0,
                    TotaPage = 0,
                    PageData = null
                };
            }
        }

        /// <summary>
        /// 根据销售订单ID查询多个物品的分页条件查询列表
        /// </summary>
        public async Task<ApiPageing<SalesOrderItemResultDto>> GetSalesOrderItemsAsync(SalesOrderItemQueryDto queryDto)
        {
            try
            {
                var query = _context.SalesOrderItems
                    .Where(soi => !soi.IsDeleted && soi.SalesOrderId == queryDto.SalesOrderId)
                    .Join(_context.Items.Where(i => !i.IsDeleted), 
                        soi => soi.ItemId, 
                        i => i.Id, 
                        (soi, i) => new { SalesOrderItem = soi, Item = i })
                    .AsQueryable();

                // 应用查询条件
                if (!string.IsNullOrEmpty(queryDto.ItemNumberOrNameOrModel))
                {
                    query = query.Where(x => 
                        x.Item.ItemNumber.Contains(queryDto.ItemNumberOrNameOrModel) ||
                        x.Item.ItemName.Contains(queryDto.ItemNumberOrNameOrModel) ||
                        x.Item.SpecificationModel.Contains(queryDto.ItemNumberOrNameOrModel));
                }

                if (!string.IsNullOrEmpty(queryDto.ItemCategory))
                {
                    query = query.Where(x => x.Item.ItemCategory == queryDto.ItemCategory);
                }

                if (!string.IsNullOrEmpty(queryDto.ItemClassification))
                {
                    query = query.Where(x => x.Item.ItemClassification == queryDto.ItemClassification);
                }

                // 获取总数
                var totalCount = await query.CountAsync();

                // 分页查询（TotalInventory 使用可翻译的子查询计算）
                var items = await query
                    .OrderBy(x => x.Item.ItemNumber)
                    .Skip((queryDto.PageIndex - 1) * queryDto.PageSize)
                    .Take(queryDto.PageSize)
                    .Select(x => new SalesOrderItemResultDto
                    {
                        Id = x.Item.Id,
                        ItemNumber = x.Item.ItemNumber,
                        ItemName = x.Item.ItemName,
                        SpecificationModel = x.Item.SpecificationModel,
                        Unit = x.Item.Unit,
                        ItemCategory = x.Item.ItemCategory,
                        ItemClassification = x.Item.ItemClassification,
                        Brand = x.Item.Brand,
                        TotalInventory = _context.ItemInventories
                            .Where(ii => !ii.IsDeleted && ii.ItemId == x.Item.Id)
                            .Select(ii => (int?)ii.Quantity)
                            .Sum() ?? 0,
                        SalesQuantity = x.SalesOrderItem.SalesQuantity
                    })
                    .ToListAsync();

                var totalPage = (int)Math.Ceiling((double)totalCount / queryDto.PageSize);

                return new ApiPageing<SalesOrderItemResultDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "查询成功",
                    TotaCount = totalCount,
                    TotaPage = totalPage,
                    PageData = items
                };
            }
            catch (Exception ex)
            {
                return new ApiPageing<SalesOrderItemResultDto>
                {
                    Code = ApiEnum.Error,
                    Msg = $"查询失败：{ex.Message}",
                    Data = null,
                    TotaCount = 0,
                    TotaPage = 0,
                    PageData = null
                };
            }
        }

        /// <summary>
        /// 获取物品概要（异步，避免在EF投影阶段捕获实例方法）
        /// </summary>
        private async Task<string> GetItemSummaryAsync(int salesOrderId)
        {
            try
            {
                var items = await _context.SalesOrderItems
                    .Where(soi => !soi.IsDeleted && soi.SalesOrderId == salesOrderId)
                    .Join(_context.Items.Where(i => !i.IsDeleted),
                        soi => soi.ItemId,
                        i => i.Id,
                        (soi, i) => new { ItemName = i.ItemName, Quantity = soi.SalesQuantity })
                    .Take(3) // 只取前3项
                    .ToListAsync();

                if (!items.Any())
                    return "无物品";

                var summary = string.Join("、", items.Select(x => $"{x.ItemName}: {x.Quantity}"));
                var totalCount = await _context.SalesOrderItems
                    .Where(soi => !soi.IsDeleted && soi.SalesOrderId == salesOrderId)
                    .CountAsync();

                if (totalCount > 3)
                    summary += $" 等{totalCount}项";

                return summary;
            }
            catch
            {
                return "获取物品概要失败";
            }
        }
    }
} 